﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Aliyun.OpenServices.OpenStorageService;
using liaowa2.Web.Models;
using yidi.Common;

namespace liaowa2.Web.tools
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {
        const string disName = "images";
        const string bucket = "liaowa";
        const string accessId = "LTAImIZnIRQM6F9M";
        const string accessKey = "XS2l7cCr0SCNfxURZSAZTnADYtxW33";

        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = context.Request["action"].Replace("video?action=UpLoadFile", "video");

            switch (action)
            {
                case "EditorFile": //编辑器文件
                    EditorFile(context);
                    break;
                case "ManagerFile": //管理文件
                    //  ManagerFile(context);
                    break;
                case "video":
                    UpVideoLoadFile(context);
                    break;
                default: //普通上传
                    UpLoadFile(context);
                    break;
            }

        }

        #region 上传文件处理===================================
        private void UpLoadFile(HttpContext context)
        {
            List<UploadFilesOutput> ufModel = new List<UploadFilesOutput>();
            HttpPostedFile file = HttpContext.Current.Request.Files[0];
            var fileLen2 = HttpContext.Current.Request.Files[0].ContentLength;
            if (fileLen2 == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传文件！\"}");
                return;
            }
            UpdateFileInputDto base64 = new UpdateFileInputDto();

            try
            {
                string fileUrls = "";
                string fileNames = "";
                string fileExts = "";
                for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                {
                    //http://liaowa.oss-cn-shanghai.aliyuncs.com/images/web/111111.png

                    var inputStream = HttpContext.Current.Request.Files[i].InputStream;
                    Aliyun.OpenServices.OpenStorageService.OssClient Oc = new Aliyun.OpenServices.OpenStorageService.OssClient("http://oss-cn-shanghai.aliyuncs.com", accessId, accessKey);

                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string fileExt = System.IO.Path.GetExtension(HttpContext.Current.Request.Files[i].FileName);
                    fileName = fileName + fileExt;

                    //var acl = Oc.GetBucketAcl(bucket);
                    Aliyun.OpenServices.OpenStorageService.PutObjectResult or = Oc.PutObject(bucket, disName + "/web/" + fileName
                        , inputStream   //HttpContext.Current.Request.Files[i].InputStream//该处有替换
                        , new Aliyun.OpenServices.OpenStorageService.ObjectMetadata());

                    fileUrls += "http://" + bucket + ".oss-cn-shanghai.aliyuncs.com/" + disName + "/web/" + fileName + ",";
                    fileNames += fileName + ",";
                    fileExts += fileExt + ",";

                }

                string msg = "{\"status\": 1, \"msg\": \"上传文件成功！\", \"name\": \""
                             + fileNames.TrimEnd(',') + "\", \"path\": \"" + fileUrls.TrimEnd(',') + "\", \"thumb\": \""
                             + "" + "\", \"size\": " + file.ContentLength + ", \"ext\": \"" + fileExts.TrimEnd(',') + "\"}";

                //返回成功信息
                context.Response.Write(msg);
                return;
            }
            catch (Exception ex)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"" + ex.Message + "\"}");
                return;
            }
        }
        #endregion

        #region 视频上传
        private void UpVideoLoadFile(HttpContext context)
        {
            int partSize = 50 * 1024 * 1024;

            HttpPostedFile file = HttpContext.Current.Request.Files[0];
            var fileLen2 = HttpContext.Current.Request.Files[0].ContentLength;
            if (fileLen2 == 0)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"请选择要上传文件！\"}");
                return;
            }

            OssClient Oc = new OssClient("http://oss-cn-shanghai.aliyuncs.com", accessId, accessKey);

            try
            {
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                var initiateRequest = new InitiateMultipartUploadRequest(bucket, fileName + ".mp4");
                var initiaUpload = Oc.InitiateMultipartUpload(initiateRequest);

                var partCount = fileLen2 / partSize;
                if (fileLen2 % partSize != 0)
                {
                    partCount++;
                }

                var partETags = new List<PartETag>();
                for (var i = 0; i < partCount; i++)
                {
                    var skipBytes = (long)partSize * i;
                    //定位到本次上传片应该开始的位置
                    file.InputStream.Seek(skipBytes, 0);
                    //计算本次上传的片大小，最后一片为剩余的数据大小，其余片都是part size大小。
                    var size = (partSize < fileLen2 - skipBytes) ? partSize : (fileLen2 - skipBytes);
                    var uploadRequest = new UploadPartRequest(initiaUpload.BucketName, initiaUpload.Key, initiaUpload.UploadId)
                    {
                        InputStream = file.InputStream,
                        PartSize = size,
                        PartNumber = i + 1
                    };

                    var uploadPart = Oc.UploadPart(uploadRequest);
                    partETags.Add(uploadPart.PartETag);
                }

                var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(initiaUpload.BucketName, initiaUpload.Key, initiaUpload.UploadId);
                foreach (var partETag in partETags)
                {
                    completeMultipartUploadRequest.PartETags.Add(partETag);
                }

                var result = Oc.CompleteMultipartUpload(completeMultipartUploadRequest);

                string msg = "{\"status\": 1, \"msg\": \"上传文件成功！\", \"name\": \""
                             + result.BucketName + "\", \"path\": \"" + result.Location + "\", \"thumb\": \""
                             + "" + "\", \"size\": " + file.ContentLength + ", \"ext\": \"" + "" + "\"}";

                //返回成功信息
                context.Response.Write(msg);
                return;
            }
            catch (Exception ex)
            {
                context.Response.Write("{\"status\": 0, \"msg\": \"" + ex.Message + "\"}");
                return;
            }
        }
        #endregion


        #region 编辑器上传处理===================================
        private void EditorFile(HttpContext context)
        {
            HttpPostedFile imgFile = context.Request.Files["imgFile"];
            if (imgFile == null)
            {
                showError(context, "请选择要上传文件！");
                return;
            }

            UpdateFileInputDto base64 = new UpdateFileInputDto();

            try
            {
                string fileUrls = "";
                string fileNames = "";
                string fileExts = "";
                for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                {
                    //http://liaowa.oss-cn-shanghai.aliyuncs.com/images/web/111111.png

                    var inputStream = HttpContext.Current.Request.Files[i].InputStream;
                    Aliyun.OpenServices.OpenStorageService.OssClient Oc = new Aliyun.OpenServices.OpenStorageService.OssClient("http://oss-cn-shanghai.aliyuncs.com", accessId, accessKey);

                    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    string fileExt = System.IO.Path.GetExtension(HttpContext.Current.Request.Files[i].FileName);
                    fileName = fileName + fileExt;

                    Aliyun.OpenServices.OpenStorageService.PutObjectResult or = Oc.PutObject(bucket, disName + "/web/" + fileName
                        , inputStream   //HttpContext.Current.Request.Files[i].InputStream//该处有替换
                        , new Aliyun.OpenServices.OpenStorageService.ObjectMetadata());

                    fileUrls += "http://" + bucket + ".oss-cn-shanghai.aliyuncs.com/" + disName + "/web/" + fileName + ",";
                    fileNames += fileName + ",";
                    fileExts += fileExt + ",";

                }

                string filePath = fileUrls.TrimEnd(',').ToString(); //取得上传后的路径
                Hashtable hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = filePath;
                context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                context.Response.Write(JsonHelper.ObjectToJSON(hash));
                //context.Response.End();
            }
            catch (Exception)
            {
                showError(context, "失败系统异常！");
                return;
            }
        }
        //显示错误
        private void showError(HttpContext context, string message)
        {
            Hashtable hash = new Hashtable();
            hash["error"] = 1;
            hash["message"] = message;
            context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
            context.Response.Write(JsonHelper.ObjectToJSON(hash));
            context.Response.End();
        }
        #endregion

        #region 浏览文件处理=====================================
        // private void ManagerFile(HttpContext context)
        //{
        //    Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();

        //    //根目录路径，相对路径
        //    String rootPath = siteConfig.webpath + siteConfig.filepath + "/"; //站点目录+上传目录
        //    //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        //    String rootUrl = siteConfig.webpath + siteConfig.filepath + "/";
        //    //图片扩展名
        //    String fileTypes = "gif,jpg,jpeg,png,bmp";

        //    String currentPath = "";
        //    String currentUrl = "";
        //    String currentDirPath = "";
        //    String moveupDirPath = "";

        //    String dirPath = Utils.GetMapPath(rootPath);
        //    String dirName = context.Request.QueryString["dir"];

        //    //根据path参数，设置各路径和URL
        //    String path = context.Request.QueryString["path"];
        //    path = String.IsNullOrEmpty(path) ? "" : path;
        //    if (path == "")
        //    {
        //        currentPath = dirPath;
        //        currentUrl = rootUrl;
        //        currentDirPath = "";
        //        moveupDirPath = "";
        //    }
        //    else
        //    {
        //        currentPath = dirPath + path;
        //        currentUrl = rootUrl + path;
        //        currentDirPath = path;
        //        moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
        //    }

        //    //排序形式，name or size or type
        //    String order = context.Request.QueryString["order"];
        //    order = String.IsNullOrEmpty(order) ? "" : order.ToLower();

        //    //不允许使用..移动到上一级目录
        //    if (Regex.IsMatch(path, @"\.\."))
        //    {
        //        context.Response.Write("Access is not allowed.");
        //        context.Response.End();
        //    }
        //    //最后一个字符不是/
        //    if (path != "" && !path.EndsWith("/"))
        //    {
        //        context.Response.Write("Parameter is not valid.");
        //        context.Response.End();
        //    }
        //    //目录不存在或不是目录
        //    if (!Directory.Exists(currentPath))
        //    {
        //        context.Response.Write("Directory does not exist.");
        //        context.Response.End();
        //    }

        //    //遍历目录取得文件信息
        //    string[] dirList = Directory.GetDirectories(currentPath);
        //    string[] fileList = Directory.GetFiles(currentPath);

        //    switch (order)
        //    {
        //        case "size":
        //            Array.Sort(dirList, new NameSorter());
        //            Array.Sort(fileList, new SizeSorter());
        //            break;
        //        case "type":
        //            Array.Sort(dirList, new NameSorter());
        //            Array.Sort(fileList, new TypeSorter());
        //            break;
        //        case "name":
        //        default:
        //            Array.Sort(dirList, new NameSorter());
        //            Array.Sort(fileList, new NameSorter());
        //            break;
        //    }

        //    Hashtable result = new Hashtable();
        //    result["moveup_dir_path"] = moveupDirPath;
        //    result["current_dir_path"] = currentDirPath;
        //    result["current_url"] = currentUrl;
        //    result["total_count"] = dirList.Length + fileList.Length;
        //    List<Hashtable> dirFileList = new List<Hashtable>();
        //    result["file_list"] = dirFileList;
        //    for (int i = 0; i < dirList.Length; i++)
        //    {
        //        DirectoryInfo dir = new DirectoryInfo(dirList[i]);
        //        Hashtable hash = new Hashtable();
        //        hash["is_dir"] = true;
        //        hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
        //        hash["filesize"] = 0;
        //        hash["is_photo"] = false;
        //        hash["filetype"] = "";
        //        hash["filename"] = dir.Name;
        //        hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
        //        dirFileList.Add(hash);
        //    }
        //    for (int i = 0; i < fileList.Length; i++)
        //    {
        //        FileInfo file = new FileInfo(fileList[i]);
        //        Hashtable hash = new Hashtable();
        //        hash["is_dir"] = false;
        //        hash["has_file"] = false;
        //        hash["filesize"] = file.Length;
        //        hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
        //        hash["filetype"] = file.Extension.Substring(1);
        //        hash["filename"] = file.Name;
        //        hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
        //        dirFileList.Add(hash);
        //    }
        //    context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
        //    context.Response.Write(JsonHelper.ObjectToJSON(result));
        //    context.Response.End();
        //}

        #region Helper
        public class NameSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.FullName.CompareTo(yInfo.FullName);
            }
        }

        public class SizeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.Length.CompareTo(yInfo.Length);
            }
        }

        public class TypeSorter : IComparer
        {
            public int Compare(object x, object y)
            {
                if (x == null && y == null)
                {
                    return 0;
                }
                if (x == null)
                {
                    return -1;
                }
                if (y == null)
                {
                    return 1;
                }
                FileInfo xInfo = new FileInfo(x.ToString());
                FileInfo yInfo = new FileInfo(y.ToString());

                return xInfo.Extension.CompareTo(yInfo.Extension);
            }
        }
        #endregion
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}